<template>
  <a-modal
    title="新建用户"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback label="用户名">
          <a-input
            placeholder="用户名"
            v-decorator="[
              'login',
              {
                rules: [
                  { required: true, message: '用户名不能为空！' },
                  { validator: checkFormLogin, trigger: 'blur' },
                ],
              },
            ]"
          />
          <!-- <p v-if="loginStatus === 0" style="color:#f00; margin:0; line-height:15px">用户名已存在！</p> -->
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="真实姓名">
          <a-input
            placeholder="真实姓名"
            v-decorator="['userName', { rules: [{ required: true, message: '真实姓名不能为空！' }] }]"
          />
        </a-form-item>
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色名称"
        >
          <a-radio-group placeholder="角色名称" v-decorator="['authorities', {rules: [{required: true, message: '真实姓名不能为空！'}]}]" >
            <a-radio :value="1">系统管理员</a-radio>
            <a-radio :value="2">维护管理员</a-radio>
            <a-radio :value="3">一般用户</a-radio>
          </a-radio-group>
        </a-form-item> -->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称" hasFeedback>
          <a-select
            style="width: 100%"
            :allowClear="true"
            placeholder="角色名称"
            v-decorator="['tRole', { rules: [{ required: true, message: '赋予权限不能为空！' }] }]"
          >
            <!-- <a-select-option v-for="(action, index) in tRoleList" :key="index" :value="action.name">{{ action.name }}</a-select-option> -->
            <a-select-option v-for="(action, index) in tRoleList" :key="index" :value="JSON.stringify(action)">{{
              action.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
          <a-select
            placeholder="状态"
            v-decorator="['activated', { rules: [{ required: true, message: '状态不能为空！' }] }]"
          >
            <a-select-option value="1">正常</a-select-option>
            <a-select-option value="0">禁用</a-select-option>
          </a-select>
          <!-- <a-switch checked-children="是" un-checked-children="否" v-decorator="['activated']" @change="checkedChange" /> -->
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback label="邮箱">
          <a-input
            placeholder="邮箱"
            id="email"
            v-decorator="[
              'email',
              {
                rules: [
                  {
                    pattern: new RegExp(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, 'g'),
                    message: '邮箱格式不正确',
                  },
                  { required: true, message: '邮箱不能为空！' },
                  { validator: checkFormEmail, trigger: 'blur' },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码">
          <a-input
            placeholder="密码"
            type="password"
            autoComplete="new-password"
            v-decorator="[
              'password',
              {
                rules: [
                  { required: true, message: '密码不能为空！' },
                  { min: 6, message: '用户名最小长度为6位' },
                  { max: 15, message: '用户名长度不可超过15位' },
                  { validator: validateToNextPassword },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="确认密码">
          <a-input
            placeholder="确认密码"
            type="password"
            v-decorator="[
              'confirm',
              { rules: [{ required: true, message: '确认密码不能为空！' }, { validator: compareToFirstPassword }] },
            ]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback label="联系电话">
          <a-input
            placeholder="联系电话"
            v-decorator="[
              'phone',
              {
                rules: [
                  { pattern: new RegExp(/^1[3|4|5|6|7|8|9]\d{9}$/, 'g'), message: '请输入正确的手机号码' },
                  { required: true, message: '联系电话不能为空！' },
                  { validator: checkFormPhone, trigger: 'blur' },
                ],
              },
            ]"
          />
        </a-form-item>
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="创建时间"
        >
          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="创建时间" @change="createdChange" v-decorator="['created_time',{rules: [{required: true, message: '创建时间不能为空！'}]}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="创建人"
        >
          <a-input placeholder="创建人" v-decorator="['created_by',{rules: [{required: true, message: '创建人不能为空！'}]}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="更新时间"
        >
          <a-date-picker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="更新时间"
            v-decorator="['update_time',{rules: [{required: true, message: '更新时间不能为空！'}]}]"
            @change="updateChange"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="修改人"
        >
          <a-input placeholder="修改人" v-decorator="['update_by',{rules: [{required: true, message: '修改人不能为空！'}]}]"/>
        </a-form-item> -->
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { getIsCheckLogin, getIsCheckEmail, getIsCheckPhone, addUsersManage } from '@/api/user'
// import { login } from '../../../api/login'
export default {
  name: 'CreateUsersManageModal',
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      loginMsg: '',
      login: '',
      phone: '',
      loginTphone: [],
      visible: false,
      activated: false,
      confirmLoading: false,
      loginStatus: 1,
      emailStatus: 1,
      phoneStatus: 1,
      // tRoleList: [],
      form: this.$form.createForm(this)
    }
  },

  // props: ['tRoleList'], // 接收父亲组建的值
  // 父组件传来的角色
  props: {
    tRoleList: {
      type: Array,
      default: null
    }
  },

  methods: {
    // 检测用户是否重复
    // checkLogin (e) {
    //   console.log('绑定用户名-----', e.target.value)
    //   if (e.target.value) {
    //     // 获取用户列表信息
    //     const filter = { login: e.target.value }
    //     getIsCheckLogin(filter).then(response => {
    //       console.log('校验用户信息----', response)
    //       this.loginStatus = response.status
    //     }).catch(error => {
    //       console.log(error)
    //     })
    //   }
    // },
    // 检测用户是否重复
    // checkEmail (e) {
    //   if (e.target.value) {
    //     // 获取用户列表信息
    //     const filter = { email: e.target.value }
    //     getIsCheckEmail(filter).then(response => {
    //       console.log('校验邮箱信息----', response)
    //       this.emailStatus = response.status
    //     }).catch(error => {
    //       console.log(error)
    //     })
    //   }
    // },
    // 检测手机是否重复
    // checkPhone (e) {
    //   if (e.target.value) {
    //     // 获取用户列表信息
    //     const filter = { phone: e.target.value }
    //     getIsCheckPhone(filter).then(response => {
    //       console.log('校验手机信息----', response)
    //       this.phoneStatus = response.status
    //     }).catch(error => {
    //       console.log(error)
    //     })
    //   }
    // },
    // 校验用户
    checkFormLogin (rule, value, callback) {
      // console.log('校验判断----', value)
      const filter = { login: value }
      getIsCheckLogin(filter).then((response) => {
        this.loginStatus = response.status
        if (this.loginStatus === 0) {
          callback(new Error('用户名已经注册'))
        } else {
          callback()
        }
      })
    },
    // 校验邮箱
    checkFormEmail (rule, value, callback) {
      const filter = { email: value }
      getIsCheckEmail(filter).then((response) => {
        this.emailStatus = response.status
        if (this.emailStatus === 0) {
          callback(new Error('邮箱已经注册'))
        } else {
          callback()
        }
      })
    },
    // 校验手机
    checkFormPhone (rule, value, callback) {
      const filter = { phone: value }
      getIsCheckPhone(filter).then((response) => {
        this.phoneStatus = response.status
        if (this.phoneStatus === 0) {
          callback(new Error('手机已经注册'))
        } else {
          callback()
        }
      })
    },
    // checkedChange (checked) {
    //   this.activated = checked
    //   console.log('a-switch to', checked)
    // },
    // 选中创建时间
    createdChange (value, dateString) {
      console.log('Formatted Selected Time: ', dateString)
    },
    // 选中创建时间
    updateChange (value, dateString) {
      console.log('Formatted Selected Time: ', dateString)
    },
    compareToFirstPassword (rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback(new Error('两次输入密码不一致'))
        // callback('Two passwords that you enter is inconsistent!')
      } else {
        callback()
      }
    },
    validateToNextPassword (rule, value, callback) {
      const form = this.form
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    add () {
      this.visible = true
    },

    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        // 删除对象中typeId
        delete values.confirm
        if (!errors) {
          // values.activated = this.activated
          console.log('values----', values)
          values.tRole = JSON.parse(values.tRole)
          values.authorities = [
            {
              name: 'ROLE_USER'
            },
            {
              name: 'ROLE_ADMIN'
            }
          ]
          values.tRole.createDate = moment.utc(values.createDate)
          values.tRole.modifyDate = moment.utc(values.modifyDate)
          addUsersManage(values).then((res) => {
            if (res) {
              // 存储成功、刷新列表
              this.$emit('ok', values)
              this.visible = false
              this.confirmLoading = false
              this.$notification['success']({
                message: '提示',
                description: '数据添加成功！'
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
    }
  }
}
</script>
